package com.phei.netty.broadcast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class LogEventBroadcaster {

		private EventLoopGroup group;
		private Bootstrap bootstrap;
		private File file;
		public LogEventBroadcaster(InetSocketAddress address,File file) {
			group = new NioEventLoopGroup();
			bootstrap = new Bootstrap();
			bootstrap.group(group)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(new LogEventEncoder(address));
			this.file = file;
		}
		public void run() {
			try {
				Channel ch = bootstrap.bind(0).sync().channel();
				long pointer = 0;
				for(;;) {
					long len = file.length();
					System.out.println("len:"+len);
					if(len < pointer) {
						pointer = len;
					}else if(len > pointer) {
						RandomAccessFile raf = new RandomAccessFile(file, "r");
						raf.seek(pointer);
						String line;
						while((line = raf.readLine()) != null) {
						ch.writeAndFlush(new LogEvent(null, -1,file.getAbsolutePath(),"dddddddddddddddd"));
						}
						pointer = raf.getFilePointer();
						raf.close();
					}
					
					Thread.sleep(5000);
					
				}
				
			} catch (InterruptedException e) {
				e.printStackTrace();
				Thread.interrupted();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				Thread.interrupted();
			} catch (IOException e) {
				e.printStackTrace();
				Thread.interrupted();
			}
			
		}
		public void stop() {
			group.shutdownGracefully();
		}
		
		public static void main(String[] args) {
			if(args.length != 2) {
				throw new IllegalArgumentException();
			}
			LogEventBroadcaster broadCaster = new LogEventBroadcaster(new InetSocketAddress("127.0.0.1",Integer.parseInt(args[0])), new File(args[1]));
			
			try {
				broadCaster.run();
			}
			finally {
				broadCaster.stop();
			}
		}
		
		
}
